package com.heatup.apt.api.controller;

import com.heatup.apt.api.service.UserSignService;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * UserSign 控制层
 *
 */
@Controller
@RequestMapping("/user/sign")
public class UserSignController extends BaseController{

    Logger logger = LoggerFactory.getLogger(UserSignController.class);

    @Resource
    private UserSignService userSignService;

    /**
     *@Author: timo
     *@Date: 2018/4/2 10:55
     *@Description:
     * 用户端 - 用户签到
     *
     */
    @ResponseBody
    @RequestMapping("/user_sign_in")
    public String userSignIn(HttpServletRequest request){
        ApiResultModel<Object> apiResultModel = new ApiResultModel<>();
        String callback = RequestTools.RequestString(request, "callback","");
        Integer courseSignId = RequestTools.RequestInt(request, "courseSignId",0);
        Integer courseId = RequestTools.RequestInt(request, "courseId",0);
        Integer orderId = RequestTools.RequestInt(request, "orderId",0);
        UserInfo userInfo = this.getUserInfo();
        if (userInfo == null){
            apiResultModel.setRet(apiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
        }
        try {
            apiResultModel = userSignService.saveUserSign(userInfo,courseSignId,courseId,orderId);
        }catch (Exception e){
            logger.error(" userSignIn | error:"+e.toString()+e.getCause(),e);
            apiResultModel.setRet(apiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());

        }
        apiResultModel.setLogined(this.isLogined());
        logger.info("resultJson:"+ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback));
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel),callback);
    }
}